package csc.fresher.finalgroupfour.controller;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import csc.fresher.finalgroupfour.domain.User;
import csc.fresher.finalgroupfour.service.BankService;

/**
 * Controller for home action.
 * 
 * @author tnguyen256
 *
 */
@Controller
public class HomeController {
	@Autowired
	private BankService bankService;
	int count = 0;

	public BankService getBankService() {
		return bankService;
	}

	@Autowired
	public void setBankService(BankService bankService) {
		this.bankService = bankService;
	}

	@RequestMapping(value = { "/", "home" })
	public ModelAndView home(HttpServletRequest request,  Principal userPrincipal) {

		ModelAndView model = new ModelAndView();

		if (userPrincipal == null) {
			model.setViewName("login");
		} else {
			HttpSession session = request.getSession();
			session.setAttribute("errorMessage", null);
			Authentication auth = SecurityContextHolder.getContext()
					.getAuthentication();
			String loginId = auth.getName(); // get logged in Id
			User user = bankService.findUser(loginId);
			user.setCount(0);
			bankService.updateUser(user);
			 model.addObject("user", user.getLoginId()); 
			model.setViewName("home");
		}
		return model;
	}

}
